package com.file.controller;


import com.file.entity.Pic;
import com.file.service.PicService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("file")
public class PicController {

    @Autowired
    private PicService picService;

    @RequestMapping()
    @ResponseBody
    public List<Pic> findALLPic(){
        List<Pic> pics = picService.selectAllPic();
        return pics;
    }

    @GetMapping("")
    public String toIndex(){
      return "index";
    }

    /**
     * 文件上传
     * @param multipartFile
     * @return
     */
    @PostMapping("upload")
    public String upload(@RequestParam("file") MultipartFile multipartFile){

       int i = picService.uploadFile(multipartFile);
       return "redirect: /index";
    }

    @RequestMapping(value = "show",method = RequestMethod.GET)
    public String show(Model model){
        List<Pic> PicList=picService.list();
        List<Pic> picNewList = new ArrayList<>();
        for (Pic pic : PicList) {
            Pic newPic = new Pic();
            BeanUtils.copyProperties(pic, newPic);
            newPic.setPicAddress("/ps/upload/" + pic.getPicAddress());
            picNewList.add(newPic);
        }
        model.addAttribute("file", picNewList);
        return "index";
    }


    @GetMapping("/get")
    public ResponseEntity<ByteArrayResource> get(@RequestParam("id") String id){
        Pic pic=picService.find(id);
        return ResponseEntity.ok()
                .contentLength(pic.getFileSize().longValue())
                .contentType(MediaType.parseMediaType(pic.getContentType()))
                .body(new ByteArrayResource(pic.getContent()));


    }

}
